package com.kevinwu.server.servlet;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServletMapper {

    private static Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();
    /**
     * 获取appBase目录下的context
     * @param appBase
     * @return
     */
    private static String getContext(String appBase){

        String context = "";
        File[] fileList = new File(appBase).listFiles();
        for (File file : fileList) {
            if(file.isDirectory()){
                context = context+file.getName()+",";
            }
        }
        return context = context.substring(0,context.length()-1);
    }
    /**
     * 返回指定路径下的web.xml文件 全路径
     * @param file
     * @return
     */
    private static String showWebxmlPath(File file){
        File[] fileList = file.listFiles();
        for (File fileName : fileList){
            if (fileName.isDirectory()){
                showWebxmlPath(fileName);
            }
            if("web.xml".equals(fileName.getName())){
                return fileName.getAbsolutePath();
            }
        }
        return "";
    }

    /**
     * 解析web.xml文件
     * @param context
     * @param filepath
     */
    private static void loadWebxml(String context, String filepath) {

        try {
            InputStream resourceAsStream = new FileInputStream(filepath);
            Document document = new SAXReader().read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");

            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put("/"+context+urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据传入的appBase查找目录下的web.xml文件，并组装成servletMapper
     * @param appBase
     * @return
     */
    public static Map<String,HttpServlet> getServletMapper(String appBase){
        String Context = getContext(appBase);
        String[] split = Context.split(",");
        for (String s : split) {
            String filepath=appBase + "/" + s;
            String s1 = showWebxmlPath(new File(filepath));
            System.out.println(s1);
            loadWebxml(s,s1);
        }
        return servletMap;
    }
}
